package com.stationbuilding.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
    /**
     * date2比date1多的天数
     *
     * @param date1
     * @return
     */
    public static int differentDaysToCurrentDate(String date1) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(strToDate(date1));
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(new Date());
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    timeDistance += 366;
                } else {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            return day2 - day1;
        }
    }

    public static Date strToDate(String str) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        //必须捕获异常
        try {
            return simpleDateFormat.parse(str);
        } catch(ParseException px) {
            return null;
        }
    }

    public static String formatDate(int year, int month, int day) {
        return year + "-" + (month > 8 ? (month + 1) : "0" + (month + 1)) + "-" + (day > 9 ? day : "0" + day);
    }
}
